<template>
    <div>
      <div class="card" >
        <el-input v-model="data.key" clearable style="width: 200px;margin-right: 10px" placeholder="请输入名称"/>
        <el-button type="warning" plain @click="load(data.key)">搜索</el-button>
        <el-button type="primary" @click="Add">新增</el-button>
        <el-button type="danger" plain @click="delAll">批量删除</el-button>
      </div>
      <div class="card" style="margin-top: 5px" >
        <el-table :data="data.tableData" :row-key="getRowKeys" @selection-change="handleSelectionChange" min-height="250" style="width: 100%">
          <el-table-column type="selection" :reserve-selection="true" width="55" />
          <el-table-column label="图片">
            <template #default="scope">
              <el-image
                  style="width: 50px; height: 50px"
                  :src="scope.row.fileimg"
                  :preview-src-list="[scope.row.fileimg]"
                  :preview-teleported="true">
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="名称" />
          <el-table-column prop="catename" label="分类" />
          <el-table-column prop="typename" label="口味" />
          <el-table-column prop="price" label="价格" />
          <el-table-column label="特价" >
            <template #default="scope">{{scope.row.tjprice}}
              <el-tag @click="tjAdd(scope.row)">设置</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="是否推荐">
            <template #default="scope">{{scope.row.istj}}
              <el-tag type="success" v-if="scope.row.istj==='否'" @click="TJedit(scope.row.id,'是')">推荐</el-tag>
              <el-tag type="danger" v-if="scope.row.istj==='是'" @click="TJedit(scope.row.id,'否')">取消</el-tag>
            </template>
          </el-table-column>
          <el-table-column  label="库存" >
            <template #default="scope">{{scope.row.kcnum}}
              <el-tag type="info" @click="KcAdd(scope.row)">添加</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button type="warning" plain size="small" @click="Edit(scope.row)">编辑</el-button>
              <el-button type="danger" plain size="small" @click="Delete(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="card" v-if="data.total>0" style="display: flex;justify-content: center">
          <el-pagination
              @current-change="load()"
              background
              layout="prev, pager, next"
              v-model:page-size="data.pageSize"
              v-model:current-page="data.pageNum"
              :total="data.total"/>
        </div>
      </div>
      <!-- 菜品信息-->
      <el-dialog :title="data.title" width="60%" v-model="data.formVisible" :close-on-click-modal="false" destroy-on-close>
        <el-form :model="data.form" ref="formRef" :rules="data.rules" label-width="100px" style="padding-right: 50px">
          <el-form-item label="图片" prop="avatar">
            <el-upload class="upload-demo"
                       :action="uploadimgUrl"
                       :limit="1"
                       list-type="picture"
                       :file-list="data.fileList"
                       accept=".jpg,.png,.jpeg,.JPG,.PNG"
                       :on-success="handleImgSuccess">
              <el-button type="primary">上传图片</el-button>
            </el-upload>
          </el-form-item>

          <el-form-item label="名称" prop="name">
            <el-input v-model="data.form.name" placeholder="请输入名称" autocomplete="off" />
          </el-form-item>
          <el-form-item label="分类" prop="categoryid">
            <el-select  style="width: 100%" v-model="data.form.categoryid">
              <el-option value="" label="请选择分类"></el-option>
              <el-option v-for="category in data.categoryList" :key="category.id" :value="category.id" :label="category.name"></el-option>
            </el-select>

          </el-form-item>
          <el-form-item label="口味" prop="typename">
            <el-radio-group v-model="data.form.typename">
              <el-radio value="特辣">特辣</el-radio>
              <el-radio value="辣">辣</el-radio>
              <el-radio value="微辣">微辣</el-radio>
              <el-radio value="清淡">清淡</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="价格" prop="price">
            <el-input type="number" v-model="data.form.price" placeholder="请输入价格" autocomplete="off" />
          </el-form-item>

          <el-form-item label="详情" >
            <div id="editor"></div>
          </el-form-item>
        </el-form>
        <template #footer>
      <span class="dialog-footer">
        <el-button @click="data.formVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">保 存</el-button>
      </span>
        </template>
      </el-dialog>
      <!-- 设置特价信息-->
      <el-dialog title="特价设置" width="60%" v-model="data.TJformVisible" :close-on-click-modal="false" destroy-on-close>
        <el-form :model="data.form" ref="formRef" :rules="data.tjrules" label-width="100px" style="padding-right: 50px">

          <el-form-item label="特价设置" prop="tjprice">
            <el-input type="number" v-model="data.form.tjprice" placeholder="请输入特价" autocomplete="off" />
          </el-form-item>

        </el-form>
        <template #footer>
      <span class="dialog-footer">
        <el-button @click="data.TJformVisible = false">取 消</el-button>
        <el-button type="primary" @click="TJsave">保 存</el-button>
      </span>
        </template>
      </el-dialog>
      <!-- 设置库存信息-->
      <el-dialog title="添加库存" width="60%" v-model="data.KcformVisible" :close-on-click-modal="false" destroy-on-close>
        <el-form :model="data.form" ref="formRef" :rules="data.Kcrules" label-width="100px" style="padding-right: 50px">

          <el-form-item label="库存数量" prop="num">
            <el-input type="number" min="1" v-model="data.form.num" placeholder="请输入库存数量" autocomplete="off" />
          </el-form-item>

        </el-form>
        <template #footer>
      <span class="dialog-footer">
        <el-button @click="data.KcformVisible = false">取 消</el-button>
        <el-button type="primary" @click="Kcsave">保 存</el-button>
      </span>
        </template>
      </el-dialog>

    </div>
</template>

<script setup>
import {createApp, onMounted, reactive, ref} from "vue";
import router from "@/router/index.js";
import request from '@/utils/request.js'
import {ElMessage, ElMessageBox} from "element-plus";
import qs from "qs";
import E from 'wangeditor'
import {sendMsg} from "@/utils/crossTagMsg.js";

//富文本编辑器
let editor;
function initwangeditor(content) { setTimeout(()=> {
  if(!editor){
    //初始化富文编辑器
    editor = new E("#editor")
    editor.config.placeholder="请输入内容"
    //上传图片
    editor.config.uploadFileName='file'
    editor.config.uploadImgServer=  import.meta.env.VITE_BASE_URL + '/fles/wang/upload?type=img'
    //上传视频
    editor.config.uploadVideoName = 'file'
    editor.config.uploadVideoServer= import.meta.env.VITE_BASE_URL + '/fles/wang/upload?type=video'
    editor.create()
  }
  editor.txt.html(content)
},0)
}

// 文件上传的接口地址
const uploadimgUrl = import.meta.env.VITE_BASE_URL + '/fles/upload'
//提交表单验证
const formRef = ref()
const data = reactive({
  key:'',
  key1:'',
  pageNum: 1,
  pageSize: 10,
  total: 0,
  formVisible: false,
  TJformVisible: false,
  KcformVisible: false,
  form: {},
  tableData:[],
  fileList:[],
  title:'',
  ids:[],
  rules:{
    name: [{ required: true, message: '名称不能为空', trigger: 'blur' },],
    categoryid: [{ required: true, message: '分类不能为空', trigger: 'blur' },],
    price: [{ required: true, message: '价格不能为空', trigger: 'blur' },],
  },
  tjrules:{
    tjprice: [{ required: true, message: '特价不能为空', trigger: 'blur' },],
  },
  Kcrules:{
    num: [{ required: true, message: '数量不能为空', trigger: 'blur' },],
  }

})

//信息列表
const load =()=>{
  request.post('/goods/list', qs.stringify({
    key:data.key,
    pageNum: data.pageNum,
    pageSize: data.pageSize,
  })).then(res => {
    data.tableData = res.data.list
    data.total = res.data.total
    sendMsg('goods更新',1)
  })
}

// 设置库存
const KcAdd = (row) => {
  data.form = JSON.parse(JSON.stringify(row))
  data.KcformVisible = true
}
// 设置特价
const tjAdd = (row) => {
  data.form = JSON.parse(JSON.stringify(row))
  data.TJformVisible = true
}

// 信息新增
const Add = () => {
  data.form = {
    typename:'微辣'
  }
  data.formVisible = true
  data.fileList = []
  editor=''
  initwangeditor("")
  data.title='菜品信息新增'
}

// 信息编辑
const Edit = (row) => {
  data.form = JSON.parse(JSON.stringify(row))
  data.formVisible = true
  data.fileList = [{name: data.form.fileimg.split('fles/').pop(), url: data.form.fileimg}];
  editor=''
  initwangeditor(row.content?data.form.content:'')
  data.title='菜品信息编辑'
}

//是否推荐
const TJedit=(id,istj)=>{
  request.post('/goods/edit', qs.stringify({
    id:id,
    istj:istj,
  })).then(res => {
    if (res.code === '200') {
      ElMessage({message: '操作成功', grouping: true, type: 'success'})
      load()
    } else {
      ElMessage.error(res.msg)
    }
  })
}

// 新增或编辑提交
const save = () => {
  data.form.content = editor.txt.html()
  formRef.value.validate((valid=>{
    if(valid){
      request.post('/goods/add', qs.stringify({
        id:data.form.id,
        name:data.form.name,
        categoryid:data.form.categoryid,
        typename:data.form.typename,
        price:data.form.price,
        fileimg:data.form.fileimg,
        content:data.form.content,
      })).then(res => {
        if (res.code === '200') {
          ElMessage.success('操作成功')
          data.formVisible = false
          load()
        } else {
          ElMessage.error(res.msg)
        }
      })
    }
  }))
}
// 设置特价
const TJsave = () => {
  formRef.value.validate((valid=>{
    if(valid){
      request.post('/goods/tj', qs.stringify({
        id:data.form.id,
        tjprice:data.form.tjprice,
      })).then(res => {
        if (res.code === '200') {
          ElMessage.success('操作成功')
          data.TJformVisible = false
          load()
        } else {
          ElMessage.error(res.msg)
        }
      })
    }
  }))
}
// 添加库存
const Kcsave = () => {
  formRef.value.validate((valid=>{
    if(valid){
      request.post('inventoryAdd', qs.stringify({
        goodsid:data.form.id,
        num:data.form.num,
      })).then(res => {
        if (res.code === '200') {
          ElMessage.success('操作成功')
          data.KcformVisible = false
          load()
        } else {
          ElMessage.error(res.msg)
        }
      })
    }
  }))
}

// 删除
const Delete = (id) => {
  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗?', { type: 'warning' }).then(res => {
    request.post('/goods/del?id=' + id).then(res => {
      if (res.code === '200') {
        load()
        ElMessage.success('操作成功')
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(err => {})
}

//解决跨分页选中后分页取消的情况
const getRowKeys = (row)=>{
  return row.id;
}

//选中需要删除的对象
const handleSelectionChange = (rows)=>{
  data.ids = rows.map(row=>row.id).join()
}
//批量删除
const delAll=()=>{
  if(data.ids.length === 0){
    ElMessage.warning({message:'请选择需要删除的项',plain:true,grouping: true})
    return
  }
  request.post('/goods/deleteAll',qs.stringify({
    vals:data.ids
  })).then(res => {
    if (res.code === '200') {
      load()
      ElMessage.success('操作成功')
    } else {
      ElMessage.error(res.msg)
    }
  })
}
// 处理文件上传的钩子
const handleImgSuccess = (res) => {
  data.form.fileimg = res.data  // res.data就是文件上传返回的文件路径，获取到路径后赋值表单的属性
}
//查询分类列表
const catelist=()=>{
  request.post('cateListAll', qs.stringify({
  })).then(res => {
    data.categoryList = res.data
  })
}
catelist()
load()



</script>
<style scoped>
</style>
